﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.Notifications.Models;
using Microhard.Core.Algorithm;
using Microhard.Notifications.Attrs;
using Microhard.Core;
using Microhard.Notifications.Enum;

namespace Microhard.Notifications.Interfaces
{
    public class NotificationMsgCreator
    {
        public static List<NotificationModel> CreateMsg(object model,string specificTemplate)
        {
            List<NotificationModel> rtn = new List<NotificationModel>();
            if (model == null)
                return rtn;

            //获得业务实体上的所有AttrOfNotiMsgTemplate标签
            var objs = AttrAlg.GetCustomerAttribute(model, typeof(AttrOfNotiMsgTemplate));
            if (objs == null)
                return rtn;
            var aomts = objs.Select(x => x as AttrOfNotiMsgTemplate).ToList();
            //选择固定模板
            if (!string.IsNullOrEmpty(specificTemplate))
            {
                aomts = aomts.Where(a => string.IsNullOrEmpty(a.Command) == false && a.Command.ToLower() == specificTemplate.ToLower()).ToList();
            }
            foreach (var aomt in aomts)
            {
                if (aomt != null)
                {
                    //获得接收人
                    INotificationScope ins = IoC.Resolve(aomt.GetSpecificUserClass) as INotificationScope;
                    var res = ins.GetReceivers(model);
                    if (res != null && res.Count > 0)
                    {
                        //获得文本消息内容
                        INotificationMsgTemplate inmt = IoC.Resolve(aomt.Template) as INotificationMsgTemplate;
                        var msg = inmt.CreateMsg(model);
                        var msgSendType = aomt.MsgType;
                        if (!string.IsNullOrEmpty(msg))
                        {
                            NotificationModel nm = new NotificationModel
                            {
                                Users = res.ToArray(),
                                Content = msg,
                                MsgType = msgSendType
                            };
                            rtn.Add(nm);
                        }
                        //获得图片内容
                        var imgs = inmt.CreateImage(model);
                        if (imgs != null && imgs.Count > 0)
                        {
                            NotificationModel nm = new NotificationModel
                            {
                                Users = res.ToArray(),
                                Images = imgs,
                                MsgType = msgSendType
                            };
                        }
                    }
                }
            }
            return rtn;
        }
    }
}
